package com.gzhryc.shared_device.oem.code.member;

import com.gzhryc.common.StringTools;
import com.gzhryc.common.json.JsonTools;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.common.redis.RedisTools;
import com.gzhryc.shared_device.base.models.VerifyCodeData;
import com.gzhryc.shared_device.oem.code.RedisDBConstants;

/**
 * 会员API回话管理
 */
public class LoginMemberSessionManager {

    static Logger log = Logger.getLogger(LoginMemberSessionManager.class);

    static LoginMemberSessionManager me;

    public static LoginMemberSessionManager self(){
        if(me == null){
            me = new LoginMemberSessionManager();
        }
        return me;
    }

    private Long times = 300L;

    public boolean setMemberSession(LoginMember loginMember){
        try {
            String json = JsonTools.toJson(loginMember);
            return RedisTools.get().set(RedisDBConstants.API_SESSION_DB, loginMember.getLoginToken(), json, times);
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        return false;
    }

    public LoginMember getMemberSession(String loginToken){
        try {
            String json = RedisTools.get().get(RedisDBConstants.API_SESSION_DB, loginToken);
            if(StringTools.isNotBlank(json)){
                return JsonTools.fromJson(json, LoginMember.class);
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        return null;
    }

    public boolean setVerifyCodeSession(VerifyCodeData verifyCodeData) {
        try {
            String json = JsonTools.toJson(verifyCodeData);
            return RedisTools.get().set(RedisDBConstants.API_SESSION_DB, verifyCodeData.getToken(), json, times);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return false;
    }

    public VerifyCodeData getVerifyCode(String token) {
        try {
            String json = RedisTools.get().get(RedisDBConstants.API_SESSION_DB, token);
            if (StringTools.isNotBlank(json)) {
                return JsonTools.fromJson(json, VerifyCodeData.class);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    public void removeVerifyCode(String token) {
        try {
            RedisTools.get().delete(RedisDBConstants.API_SESSION_DB, token);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
}
